﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.IO
{
    /// <summary>
    /// 文件压缩和文件解压
    /// </summary>
    public static class CompressHelper
    {
        /// <summary>
        /// 文件压缩
        /// </summary>
        /// <param name="fileToCompress"></param>
        /// <returns></returns>
        public static FileInfo Compress(this FileInfo fileToCompress)
        {
            string directoryPath = Path.GetDirectoryName(fileToCompress.FullName);
            //原始文件流
            using (FileStream originalFileStream = new FileStream(fileToCompress.FullName, FileMode.Open, FileAccess.Read))
            {

                if ((System.IO.File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                {
                    //目标文件流 compressedFileStream
                    using (FileStream compressedFileStream = System.IO.File.Create(fileToCompress.FullName + ".gz"))
                    {
                        //压缩流compressionStream      
                        using (GZipStream compressionStream = new GZipStream(
                            compressedFileStream,
                            CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);
                        }
                    }
                }
            }

            FileInfo info = new FileInfo(directoryPath + Path.DirectorySeparatorChar + fileToCompress.Name + ".gz");
            //Console.WriteLine($"Compressed {fileToCompress.Name} from {fileToCompress.Length.ToString()} to {info.Length.ToString()} bytes.");
            return info;
        }


        /// <summary>
        /// 文件解压
        /// </summary>
        /// <param name="fileToDecompress"></param>
        public static void Decompress(this FileInfo fileToDecompress)
        {
            using (FileStream originalFileStream = fileToDecompress.OpenRead())
            {
                string currentFileName = fileToDecompress.FullName;
                string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

                using (FileStream decompressedFileStream = System.IO.File.Create(newFileName))
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(decompressedFileStream);
                        // Console.WriteLine($"Decompressed: {fileToDecompress.Name}");
                    }
                }
            }
        }

    }
}
